<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            margin: 0;
        }
        .box {
            width: 100px;
            height: 100px;
            background: red;
        }
    </style>
</head>
<body>
    <div class="box"></div>

    <script>

        const box = document.querySelector('.box');

        // 初始的位置(为了算当前移动的距离)
        let initX = 0;
        let initY = 0;

        // 记录上次位置
        let lastX = 0;
        let lastY = 0;

        // 当前移动的距离
        let translateX = 0;
        let translateY = 0;

        function onTouchMove (e) {

            e.preventDefault();

            const x = e.touches[0].pageX;
            const y = e.touches[0].pageY;

            translateX = x - initX;
            translateY = y - initY;

            // translate(移动的x, 移动的y);
            // 上次的位置+移动的距离
            // 拖动组件/拖动库
            // 高端了: CSS  5  面试
            // left top 会引起页面元素的重排
            // translate只能一起重绘
            box.setAttribute('style', `transform: translate(${lastX + translateX}px, ${lastY + translateY}px)`);

        }

        box.addEventListener('touchstart', function (e) {
            initX = e.touches[0].pageX;
            initY = e.touches[0].pageY;
            box.addEventListener('touchmove', onTouchMove);
        });

        box.addEventListener('touchend', function () {
            lastX += translateX;
            lastY += translateY;

            box.removeEventListener('touchmove', onTouchMove);
        });

    </script>
</body>
</html>